
package com.adee.java.exception;

/*
java异常机制：
Throwable的两个子类Error和Exception，Exception的子类RuntimeException和其他Exception（IOException等）。

何时执行finally块？
当try或catch中遇到异常或return时，先跳到finally块中执行，
如果finally中有return，则直接执行return，没有return，则继续原先的return返回值。
 */
public class ExceptionTest {
    public static void main(String[] args) {
        System.out.println(test()); // 2
        System.out.println(test1()); // 1
        System.out.println(test2()); // 6
        System.out.println(test3()); // 1
    }

    public static int test() { // 2
        try {
            System.out.println("try block");
            int i = 1 / 0;
            return 0;
        }catch (Exception e) {
            System.out.println("catch block");
            return 1;
        }finally {
            System.out.println("finally block");
            return 2;
        }
    }

    public static int test1() { // 1
        int ret = 1;
        try {
            System.out.println("try block");
            int i = 1 / 0;
            return ret;
        }catch (Exception e) {
            System.out.println("catch block");
            return ret;
        }finally {
            System.out.println("finally block");
            ret = 3;
        }
    }

    public static int test2() { // 6
        int ret = 1;
        try {
            System.out.println("try block");
            int i = 1 / 0;
            return ret;
        }catch (Exception e) {
            System.out.println("catch block");
            return ret;
        }finally {
            System.out.println("finally block");
            ret = 3;
            return 6; // 执行此处return
        }
    }

    public static int test3() { // 1
        int ret = 1;
        try {
            System.out.println("try block");
            int i = 1 / 0;
            ret = 7;
            return ret;
        }catch (Exception e) {
            System.out.println("catch block");
            return ret; // 执行此处return，为1
        }finally {
            System.out.println("finally block");
        }
    }
}
